﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpectationClient.DataBaseDescription {
    [Serializable()]
    public class DataBaseInfo : Dictionary<String, SchemaInfo> {
        private String name;
        public String Name { get { return this.name; } }

        public DataBaseInfo(String dataBaseName) {
            this.name = dataBaseName;
        }

        new public void Add(String schemaName, SchemaInfo schemaInfo) {
            if(schemaName != schemaInfo.Name) throw new Exception("schemaName and schemaInfo.Name do not match");
            this.Add(schemaInfo);
        }
        public void Add(SchemaInfo schemaInfo) {
            if(schemaInfo.DataBase != null) {
                throw new Exception(
                    String.Format("SchemaInfo {0} already belongs to DataBaseDescription {1}",
                    schemaInfo.Name, schemaInfo.DataBase.Name));
            } else {
                schemaInfo.DataBase = this;
            }
            base.Add(schemaInfo.Name, schemaInfo);
        }
        

        public SchemaInfo createSchema(String schemaName) {
            SchemaInfo schemaInfo = new SchemaInfo(schemaName);
            this.Add(schemaName, new SchemaInfo(schemaName));
            return schemaInfo;
        }

        public TableInfo createTable(String schemaName, String tableName) {
            SchemaInfo si = (this.ContainsSchema(schemaName)) ? this[schemaName] : this.createSchema(schemaName);
            TableInfo ti = new TableInfo(tableName);
            si.Add(ti);
            return ti;
        }

        public bool ContainsSchema(String schemaName) {
            return this.Keys.Contains(schemaName);
        }
        public bool ContainsSchema(SchemaInfo schemaInfo) {
            return this.Values.Contains(schemaInfo);
        }

        public bool ContainsTable(String schemaName, String tableName) {
            if(!this.ContainsSchema(schemaName)) return false;
            return this[schemaName].ContainsKey(tableName);
        }
        public bool ContainsColumn(String schemaName, String tableName, String columnName) {
            if(!this.ContainsTable(schemaName, tableName)) return false;
            return this[schemaName][tableName].ContainsKey(columnName);
        }



       public int CountTables() {
            int cnt = 0;
            foreach(SchemaInfo si in this.Values) cnt += si.Count;
            return cnt;
        }

        public int CountTables(String schemaName) {
            return this[schemaName].Count;
        }

        public override string ToString() {
            return String.Format("DataBaseInfo:{0}", this.Name);
        }
    }
}
